package com.laoli.lab40;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * completeOnTimeout() 示例
 */
public class CompleteOnTimeoutDemo {
    public static void main(String[] args) throws InterruptedException {
        // 异步任务(耗时2s)
        CompletableFuture.supplyAsync(() -> {
                    System.out.println("【异步任务】开始");
                    try {
                        Thread.sleep(2000); // 休眠2s
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    return "异步任务结果"; // 返回结果
                })
                // 超时等待1s，发生异常则立即返回默认值
                .completeOnTimeout("默认值", 1000, TimeUnit.MILLISECONDS)
                // 输出任务结果(方法引用)
                .thenAccept(System.out::println);

        // 主线程休眠
        Thread.sleep(3000);
    }
}
